package com.chr.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.chr.entity.PageBean;
import com.chr.run.StartupRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chr.entity.Link;
import com.chr.service.LinkService;

/**
 * 管理员-友情链接控制器
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/admin/link")
public class LinkAdminController {

	@Autowired
	private LinkService linkService;

	@Autowired
	private StartupRunner startupRunner;
	


	/**
	 * 根据条件分页查询友情链接
	 * @param page
	 * @param limit
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/list")
	public Map<String,Object> list(@RequestParam(value="page",required=false)Integer page,@RequestParam(value="limit",required=false)Integer limit)throws Exception{
		Map<String, Object> resultMap = new HashMap<>();
		PageBean pageBean=new PageBean(page,limit);
		Map<String,Object> map=new HashMap<>();
		map.put("start",pageBean.getStart());
		map.put("size",pageBean.getPageSize());
		List<Link> linkList=linkService.list(map);
		Long count=linkService.getTotal(map);
		resultMap.put("code", 0);
		resultMap.put("count", count);
		resultMap.put("data", linkList);
		return resultMap;
	}
	
	/**
	 * 添加或者修改友情链接
	 * @param link
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/save")
	public Map<String,Object> save(Link link){
		if(link.getId()==null){
			linkService.add(link);
		}else{
			linkService.update(link);
		}
		startupRunner.loadData();
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("success", true);
		return resultMap;
	}
	
	/**
	 * 删除友情链接
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public Map<String,Object> delete(Integer id)throws Exception{
		Map<String, Object> resultMap = new HashMap<>();
		linkService.delete(id);
		startupRunner.loadData();
		resultMap.put("success", true);
		return resultMap;
	}
	
	/**
	 * 根据id查询友情链接实体
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/findById")
	public Map<String,Object> findById(Integer id)throws Exception{
		Map<String, Object> resultMap = new HashMap<>();
		Link link=linkService.findById(id);
		resultMap.put("link", link);
		resultMap.put("success", true);
		return resultMap;
	}
}
